<?php
/**
 * @desc    售后接口数据转换
 * @author: jintao
 * @since: 2016/7/21
 */
class erpapi_shop_response_aftersalev2 extends erpapi_shop_response_abstract {
    static public $refund_status = array(
        'WAIT_SELLER_AGREE'=>'0',
        'WAIT_BUYER_RETURN_GOODS'=>'2',//卖家已经同意退款
        'SELLER_REFUSE_BUYER'=>'3',//卖家拒绝seller_refuse
        'CLOSED'=>'3',//退款关闭
        'SUCCESS'=>'4',//退款成功
        // 'WAIT_SELLER_CONFIRM_GOODS'=>'6',//买家已经退货 对应何流程？不处理
    );

    static public  $return_status = array(
        'WAIT_SELLER_AGREE'=>'1',
        'WAIT_BUYER_RETURN_GOODS'=>'3',//卖家已经同意退款
        'SELLER_REFUSE_BUYER'=>'5',//卖家拒绝
        'CLOSED'=>'5',//退款关闭
        'SUCCESS'=>'4',//退款成功
        'WAIT_SELLER_CONFIRM_GOODS'=>'6',//买家已经退货
    );

    static public $reship_status = array(
        'confirm_failed'            =>  '5',
        'wait_buyer_return_goods'   =>  '0',
        'wait_seller_confirm_goods' =>  '1',
        'confirm_success'           =>  '7',
    );

    protected function _formatAddParams($params) {
        $sdf = array(
            'order_bn' => $params['tid'],
            'refund_bn' => $params['refund_id'],
            'status' => $params['status'],
            'refund_fee' => $params['refund_fee'] ? sprintf('%.2f', $params['refund_fee']) : 0,
            'refund_type' => $params['refund_type'],
            'reason' => $params['reason'],
            'modified' => $params['modified'] ? kernel::single('ome_func')->date2time($params['modified']) : '',
            'created' => $params['created'] ? kernel::single('ome_func')->date2time($params['created']) : time(),
            't_begin' => $params['t_begin'] ? kernel::single('ome_func')->date2time($params['t_begin']) : '',
            'cur_money' => $params['cur_money'],
            'pay_type' => $params['pay_type'] ? $params['pay_type'] : 'online',
            'alipay_no' => $params['alipay_no'],
            'payment' => $params['payment'],
            'account' => $params['account'],
            'bank' => $params['bank'],
            'buyer_nick' => $params['buyer_nick'],
            'desc' => $params['desc'],
            'shipping_type' => $params['shipping_type'],
            'logistics_company' => $params['logistics_company'] ? $params['logistics_company'] : $params['company_name'],
            'logistics_no' => $params['logistics_no'] ? $params['logistics_no'] : $params['sid'],
            'pay_account' => $params['pay_account'],
            'has_good_return' => $params['has_good_return'] ? strtolower($params['has_good_return']) : '',
            'good_return_time' => $params['good_return_time'] ? strtotime($params['good_return_time']) : '',
            'refund_item_list' => $params['refund_item_list'] ? json_decode($params['refund_item_list'],true) : '',
        );
        $sdf['t_ready']    = $sdf['t_begin'];
        $sdf['t_sent']     = $sdf['modified'];
        self::trim($sdf);
        return $sdf;
    }

    /**
     * @param array $sdf
     * @param array $convert 例 array('sdf_field'=>'item_id','order_field'=>'shop_goods_id','default_field'=>'outer_id');
     * @return array 返回 以bn作主键的数组 捆绑商品使用捆绑商品的bn
     */
    protected function _formatAddItemList($sdf, $convert = array()) {
        if(empty($convert)) {
            return array();
        }
        $itemList = $sdf['refund_item_list']['return_item'];
        $sdfField = $convert['sdf_field'];
        $orderField = $convert['order_field'];
        $defaultField = $convert['default_field'];
        $arrOrderField = array();
        foreach($itemList as $val) {
            if($val[$sdfField]) {
                $arrOrderField[] = $val[$sdfField];
            }
        }
        $filter = array(
            $orderField => $arrOrderField,
            'order_id' => $sdf['order']['order_id']
        );
        $object = app::get('ome')->model('order_objects')->getList($orderField . ', bn', $filter);
        $arrBn = array();
        foreach($object as $oVal) {
            $arrBn[$oVal[$orderField]] = $oVal['bn'];
        }
        $arrItem = array();
        foreach ($itemList as $item) {
            $item['bn'] = $arrBn[$item[$sdfField]] ? $arrBn[$item[$sdfField]] : $item[$defaultField];
            if($item['nums'] && !$item['num']) {
                $item['num'] = $item['nums'];
                unset($item['nums']);
            }
            if($arrItem[$item['bn']]) {
                $arrItem[$item['bn']]['num'] += $item['num'];
            } else {
                $arrItem[$item['bn']] = $item;
            }
        }

        return $arrItem;
    }

    #重新计算单价($refundItems 以bn作主键的数组 捆绑商品使用捆绑商品的bn)
    protected function _calculateAddPrice($refundItems, $sdf) {
        if(empty($refundItems)) {
            return array();
        }
        $order = $sdf['order'];
        $orderNumPrice = kernel::single('ome_order_object_item')->getNumPrice(array($order['order_id']));
        $return = $productSend = array();
        foreach($orderNumPrice[$order['order_id']] as $obj) {
            if($obj['obj_type'] == 'pkg') {
                if($refundItems[$obj['bn']]) {
                    $radio = $refundItems[$obj['bn']]['num']/$obj['quantity'];
                    foreach($obj['order_items'] as $item) {
                        $num = (int) $radio * $item['nums'];
                        $price = $obj['sale_price']/$obj['item_nums'];
                        $tmpReturn = array(
                            'bn' => $item['bn'],
                            'price' => sprintf('%.2f', $price),
                            'num' => $num,
                        );
                        $return[] = array_merge((array)$refundItems[$obj['bn']], $tmpReturn);
                        $productSend[$item['bn']] += $item['sendnum'];
                    }
                    unset($refundItems[$obj['bn']]);
                    continue;
                }
            }
            foreach($obj['order_items'] as $item) {
                if($refundItems[$item['bn']]) {
                    $tmpReturn = array(
                        'bn' => $item['bn'],
                        'price' => sprintf('%.2f', $item['sale_price'] / $item['nums']),
                        'num' => $refundItems[$item['bn']]['num'],
                    );
                    $return[] = array_merge((array)$refundItems[$item['bn']], $tmpReturn);
                    $productSend[$item['bn']] += $item['sendnum'];
                    unset($refundItems[$item['bn']]);
                }
            }
        }
        if($refundItems && is_array($refundItems)) {
            $return = array_merge(array_values($refundItems), $return);
        }

        $productData = kernel::single('material_basic_select')->getlist('material_name,material_bn,bm_id', array('material_bn'=>array_keys($productSend)));

        $product = array();
        foreach($productData as $pd) {
           
            $product[$pd['bn']] = array(
                'product_id'    => $pd['product_id'],
                'bn'            => $pd['bn'],
                'name'          => $pd['name'],
            );
        }
       
        $items = array();
        foreach($return as $value) {
            if($items[$value['bn']]) {
                $itemNum = $items[$value['bn']]['num'];
                $items[$value['bn']]['num'] += $value['num'];
                $itemPrice = ($items[$value['bn']]['price'] * $itemNum + $value['price'] * $value['num'])/$items[$value['bn']]['num'];
                $items[$value['bn']]['price'] = sprintf('%.2f', $itemPrice);
            } else {
                $items[$value['bn']] = $value;
                $items[$value['bn']]['sendNum'] = $productSend[$value['bn']];
                $items[$value['bn']]['product_id'] = $product[$value['bn']]['product_id'];
                $items[$value['bn']]['name'] = $product[$value['bn']]['name'];
            }
        }
       
        return array_values($items);
    }

    protected function _getAddType($sdf) {
        return '';
    }

    #return array('model'=>'', 'data'=>array())
    protected function _refundApplyAdditional($sdf) {
        return array();
    }

    #退款单 退款申请单 数据转换
    protected function _refundAddSdf($sdf) {
        $sdf['status'] = self::$refund_status[strtoupper($sdf['status'])];
        $refundApplyBn = $sdf['refund_bn'];
        if($sdf['reason']) {
            if(preg_match('/#(\d+)#/', $sdf['reason'],$matches)) {
                $refundApplyBn = $matches[1];
            }
            $sdf['reason'] = preg_replace('/#(\d+)#/', '', $sdf['reason']);
        }
        $shopId = $this->__channelObj->channel['shop_id'];
        // 退款申请单
        $refundApplyModel = app::get('ome')->model('refund_apply');
        $refundApply = $refundApplyModel->getList('apply_id,return_id,refund_apply_bn,refund_refer,status,money,payment,memo,addon,outer_lastmodify', array('refund_apply_bn'=>$refundApplyBn,'shop_id'=>$shopId), 0, 1);
        $sdf['refund_version_change'] = false;
        if($refundApply) {
            $sdf['refund_apply'] = $refundApply[0];
            if ($sdf['modified'] > $sdf['refund_apply']['outer_lastmodify'] && ($sdf['refund_apply']['memo'] != $sdf['reason'] || $sdf['refund_apply']['money'] != $sdf['refund_fee'])) {
                $sdf['refund_version_change'] = true;
            }
        }
        // 退款单
        $refundModel = app::get('ome')->model('refunds');
        $refund = $refundModel->getList('refund_id', array('refund_bn'=>$sdf['refund_bn'],'shop_id'=>$shopId));
        if($refund) {
            $sdf['refund'] = $refund[0];
        }
        $payment_cfg = $this->get_payment($sdf['payment'],$sdf['shop_type']);
        if($payment_cfg) {
            $sdf['payment'] = $payment_cfg['id'];
        }
        if ($sdf['status'] == '4' || $sdf['refund_type'] == 'refund') {
            $this->__apilog['title'] = '店铺(' . $this->__channelObj->channel['name'] . ')退款单，单号：' . $sdf['refund_bn'];
            $sdf['response_bill_type'] = 'refund';
        } elseif($sdf['refund_type'] == 'apply') {
            $this->__apilog['title'] = '店铺(' . $this->__channelObj->channel['name'] . ')退款申请单，单号：' . $sdf['refund_bn'];
            if ($sdf['status'] == '0' || empty($sdf['refund_apply'])) {
                $sdf['table_additional'] = $this->_refundApplyAdditional($sdf);
            }
            $sdf['response_bill_type'] = 'refund_apply';
        }
        return $sdf;
    }

    #return array('model'=>'', 'data'=>array())
    protected function _returnProductAdditional($sdf) {
        return array();
    }

    protected function _getOrderDelivery($sdf) {
        #获取订单关联的所有已发货的发货单delivery_id
        $sql = "SELECT dord.delivery_id, d.branch_id FROM sdb_ome_delivery_order AS dord
                  LEFT JOIN sdb_ome_delivery AS d ON(dord.delivery_id=d.delivery_id)
                  WHERE dord.order_id='".$sdf['order']['order_id']."'
                    AND (d.parent_id=0 OR d.is_bind='true')
                    AND d.disabled='false' AND d.status='succ'";
        $result = kernel::database()->select($sql);
        if(count($result) > 1 && !empty($sdf['refund_item_list'])) {
            $arrDelivery = array();
            foreach ($result as $key => $val) {
                $arrDelivery[$val['delivery_id']] = $val;
            }
            $productId = '';
            foreach($sdf['refund_item_list'] as $iVal) {
                if($iVal['product_id']) {
                    $productId = $iVal['product_id'];
                    break;
                }
            }
            $deliItemModel = app::get('ome')->model('delivery_items');
            $itemData = $deliItemModel->getList('delivery_id', array('delivery_id'=>array_keys($arrDelivery), 'product_id'=>$productId), 0, 1);
        }
        return $itemData ? $arrDelivery[$itemData[0]['delivery_id']] : $result[0];
    }

    protected function _returnProductReship($returnProductId, $orderId) {
        $rs = array();
        $oReship = app::get('ome')->model('reship');
        $field = 'reship_id,reship_bn,return_id,is_check,return_logi_name,return_logi_no,outer_lastmodify';
        $reship = $oReship->getList($field, array('return_id' => $returnProductId), 0, 1);
        if($reship) {
            $rs['reship'] = $reship[0];
            $otherFilter = ' AND r.reship_id != ' . $rs['reship']['reship_id'];
        }
        $sql = "SELECT i.bn, i.num FROM sdb_ome_reship as r left join sdb_ome_reship_items as i on r.reship_id=i.reship_id WHERE i.return_type='return' AND r.is_check!='5' AND r.order_id='" . $orderId . "' " . $otherFilter;
        $otherReship = $oReship->db->select($sql);
        if($otherReship) {
            $rs['other_reship_items'] = $otherReship;
        }
        return $rs;
    }

    #售后申请单数据转换
    protected function _returnProductAddSdf($sdf) {
        $this->__apilog['title'] = '店铺(' . $this->__channelObj->channel['name'] . ')售后申请单，单号：' . $sdf['refund_bn'];
        $sdf['response_bill_type'] = 'return_product';
        $sdf['status'] = self::$return_status[strtoupper($sdf['status'])];
        $returnModel = app::get('ome')->model('return_product');
        $tgReturn = $returnModel->getList('*', array('shop_id'=>$sdf['shop_id'],'return_bn'=>$sdf['refund_bn']));
        $sdf['refund_version_change'] = false;
        if($tgReturn) {
            $sdf['return_product'] = $tgReturn[0];
            if ($sdf['modified'] > $sdf['return_product']['outer_lastmodify'] && ($sdf['return_product']['content']!=$sdf['reason']) || $sdf['return_product']['money']!=$sdf['refund_fee']) {
                $sdf['refund_version_change'] = true;
            }
            $reshipData = $this->_returnProductReship($sdf['return_product']['return_id'], $sdf['order']['order_id']);
            if($reshipData['reship']) {
                $sdf['reship'] = $reshipData['reship'];
            }
            if($reshipData['other_reship_items']) {
                $sdf['other_reship_items'] = $reshipData['other_reship_items'];
            }
        }
        if ($sdf['status'] == '1' || !$sdf['return_product']) {
            // 如果前端传了会员名
            if ($sdf['buyer_nick']) {
                $shopMemberModel = app::get('ome')->model('shop_members');
                $member = $shopMemberModel->getList('member_id', array('shop_member_id' => $sdf['buyer_nick'], 'shop_id' => $sdf['shop_id']), 0, 1);
                $sdf['member_id'] = $member[0]['member_id'];
            } else {
                $sdf['member_id'] = $sdf['order']['member_id'];
            }
            $delivery = $this->_getOrderDelivery($sdf);
            if ($delivery) {
                $sdf['delivery_id'] = $delivery['delivery_id'];
                $sdf['branch_id'] = $delivery['branch_id'];
            }
            $sdf['table_additional'] = $this->_returnProductAdditional($sdf);
        } else {
            $returnItemModel = app::get('ome')->model('return_product_items');
            $tgReturnItems = $returnItemModel->getList('item_id',array('return_id'=>$sdf['return_product']['return_id']));
            if (!$tgReturnItems) {
                $this->__apilog['result']['msg'] = '缺少明细';
                return false;
            }
        }
        $sdf['choose_type_flag'] = 1;
        return $sdf;
    }

    protected function _reshipAddItemList($sdf) {
        $returnList = array();
        $itemsObj = app::get('ome')->model('return_product_items');
        $refundItemList = $itemsObj->getList('product_id,bn,name,num,price',array('return_id'=>$sdf['return_product']['return_id']));
        if($refundItemList) {
            $arrItem = array();
            foreach ($refundItemList as $val) {
                $arrItem[$val['bn']] = $val;
            }
            $returnList = $this->_calculateAddPrice($arrItem, $sdf);
        }
        return $returnList;
    }

    #退后单数据转换
    protected function _reshipAddSdf($sdf) {
        $this->__apilog['title'] = '店铺(' . $this->__channelObj->channel['name'] . ')退货单，单号：' . $sdf['refund_bn'];
        $sdf['response_bill_type'] = 'reship';
        $sdf['status'] = self::$reship_status[$sdf['status']];
        $sdf['shop_id'] = $this->__channelObj->channel['shop_id'];
        // 售后单
        $returnFilter = array('shop_id'=>$sdf['shop_id'],'return_bn'=>$sdf['refund_bn'],'source'=>'matrix');
        $returnModel = app::get('ome')->model('return_product');
        $tgReturn = $returnModel->getList('return_id,delivery_id,status,money,is_fail', $returnFilter, 0, 1);
        if (!$tgReturn) {
            //单拉售后单
            $returnRsp = kernel::single('erpapi_router_request')->set('shop', $sdf['shop_id'])->finance_getRefundDetail($sdf['refund_bn'],$sdf['refund_phase'], $sdf['order_bn']);
            if ($returnRsp['rsp'] == 'succ') {
                $msg = '';
                $rs = kernel::single('ome_return')->get_return_log($returnRsp['data'],$sdf['shop_id'],$msg);
                if ($rs) {
                    $tgReturn = $returnModel->getList('return_id,delivery_id,status,money,is_fail', $returnFilter, 0, 1);
                }
            }
        }
        if (!$tgReturn) {
            //单拉售后单
            $this->__apilog['result']['msg'] = "售后申请单不存在,不可以创建退货单!";
            return false;
        }
        if($tgReturn[0]['is_fail'] == 'true') {
            $this->__apilog['result']['msg'] = "售后申请单处于失败状态,不可以创建退货单!";
            return false;
        }
        $sdf['return_product'] = $tgReturn[0];
        $sdf['refund_item_list'] = $this->_reshipAddItemList($sdf);
        $oDc = app::get('ome')->model('dly_corp');
        $dcData = $oDc->getList('name', array('corp_id'=>$sdf['order']['logi_id']), 0, 1);
        $sdf['logi_name'] = $dcData[0]['name'];
        $Odelivery = app::get('ome')->model('delivery');
        $deliveryinfo = $Odelivery->getList('branch_id', array('delivery_id'=>$sdf['return_product']['delivery_id']), 0, 1);
        $sdf['branch_id'] = $deliveryinfo[0]['branch_id'];
        $reshipData = $this->_returnProductReship($sdf['return_product']['return_id'], $sdf['order']['order_id']);
        if($reshipData['reship']) {
            $sdf['reship'] = $reshipData['reship'];
        }
        if($reshipData['other_reship_items']) {
            $sdf['other_reship_items'] = $reshipData['other_reship_items'];
        }
        return $sdf;
    }

    public function add($params){
        $this->__apilog['title'] = '店铺(' . $this->__channelObj->channel['name'] . ')售后业务处理[订单：' . $params['tid'] . ']';
        $this->__apilog['original_bn'] = $params['tid'];
        $this->__apilog['result']['data'] = array('tid'=>$params['tid'],'aftersale_id'=>$params['refund_id'],'retry'=>'false');
        $sdf = $this->_formatAddParams($params);
        error_log(var_export($sdf,1),3,'/data/www/oms/data/aftersale.log');
        if(empty($sdf)) {
            if(!$this->__apilog['result']['msg']) {
                $this->__apilog['result']['msg'] = '不接收售后单';
            }
            return false;
        }
        $shopId = $sdf['shop_id'] = $this->__channelObj->channel['shop_id'];
        $sdf['shop_type'] = $this->__channelObj->channel['shop_type'];
        $field = 'order_id,status,process_status,ship_status,pay_status,payed,cost_payment,pay_bn,member_id,logi_id,logi_no,ship_name,ship_area,ship_addr,ship_zip,ship_tel,ship_email,ship_mobile,shipping,is_protect,is_cod';
        $tgOrder = $this->getOrder($field, $shopId, $sdf['order_bn']);
        if (!$tgOrder) {
            
            $this->__apilog['result']['msg'] = '没有订单' . $sdf['order_bn'];
            return false;
        }
        $sdf['order'] = $tgOrder;
        $type = $this->_getAddType($sdf);
        if(empty($type)) {
            if(!$this->__apilog['result']['msg']) {
                $this->__apilog['result']['msg'] = '不接收售后单';
            }
            return false;
        }
        if(is_array($sdf['refund_item_list'])) {
            $refundItemList = $this->_formatAddItemList($sdf);
            if(empty($refundItemList)) {
                $sdf['refund_item_list'] = '';
            }else{
                $sdf['refund_item_list'] = $this->_calculateAddPrice($refundItemList, $sdf);
            }
        }
        
        if($type == 'refund') {
            return $this->_refundAddSdf($sdf);
        } elseif( $type == 'returnProduct') {
            return $this->_returnProductAddSdf($sdf);
        } elseif($type == 'reship') {
            return $this->_reshipAddSdf($sdf);
        } else {
            if(!$this->__apilog['result']['msg']) {
                $this->__apilog['result']['msg'] = '不接收售后单';
            }
            return false;
        }
    }
}
